package com.nebula.sirius.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.nebula.sirius.entity.SyntaxRecordEntity;
import com.nebula.sirius.kit.StrKit;
import com.nebula.sirius.repository.SyntaxRecordRepository;
import com.nebula.sirius.service.SyntaxRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by Destiny on 03/31/2018 09:32.
 * Saturday.
 */
@Service
@Transactional
public class SyntaxRecordServiceImpl implements SyntaxRecordService {

    @Autowired
    private SyntaxRecordRepository syntaxDao;

    @Override
    public Page<SyntaxRecordEntity> getSyntax(int page, int size, String searchStr) {

        Sort sort = Sort.by("syntaxType").ascending().and(Sort.by("syntaxId").ascending());

        HashMap searchMap = JSONObject.parseObject(searchStr, HashMap.class);
        String syntaxType =
                searchMap.containsKey("syntaxType") ? searchMap.get("syntaxType").toString() : "";
        String syntaxContent =
                searchMap.containsKey("syntaxContent") ? searchMap.get("syntaxContent").toString() : "";

        PageRequest pageRequest = PageRequest.of(page - 1, size, sort); // page从0开始，前台从1开始

        Specification condition = (root, criteriaQuery, criteriaBuilder) -> {

            List<Predicate> predicates = new ArrayList<>();
            if (!StringUtils.isEmpty(syntaxType)) {
                predicates.add(criteriaBuilder.equal(root.get("syntaxType"), syntaxType));
            }
            if (!StringUtils.isEmpty(syntaxContent)) {
                predicates.add(criteriaBuilder.like(root.get("syntaxContent"), "%" + syntaxContent + "%"));
            }

            return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
        };

        return syntaxDao.findAll(condition, pageRequest);
    }

    @Override
    public void saveSyntax(SyntaxRecordEntity syntaxRecordEntity) {
        syntaxRecordEntity.setSyntaxCreateTime(StrKit.getStringDate());
        syntaxDao.save(syntaxRecordEntity);
    }

    @Override
    public void deleteSyntax(SyntaxRecordEntity syntaxRecordEntity) {
        syntaxDao.delete(syntaxRecordEntity);
    }

}
